import { is } from '@electron-toolkit/utils'
import sqliteDB from 'better-sqlite3'
import { app } from 'electron'
import path from 'path'
const dbDir = app.getPath('userData')
const dbPath = path.join(dbDir, 'my-db.sqlite')
const db = new sqliteDB(is.dev ? './example.sqlite' : dbPath)

// 初始化表
function initDB() {
  db.prepare(
    `
    CREATE TABLE IF NOT EXISTS users (
      id INTEGER PRIMARY KEY AUTOINCREMENT,
      name TEXT NOT NULL,
      age INTEGER
    )
  `
  ).run()
}

// 插入数据
function insertUser(name, age) {
  const stmt = db.prepare('INSERT INTO users (name, age) VALUES (?, ?)')
  stmt.run(name, age)
}

// 查询所有用户
function getAllUsers() {
  const stmt = db.prepare('SELECT * FROM users')
  return stmt.all() // 返回数组
}

export { initDB, insertUser, getAllUsers }
